let timer;

function request(url, method, params, header) {
  header = header || {};
  timer = setTimeout(() => {
    uni.showLoading({
      title: '加载中'
    });
  }, 500);
  setTimeout(() => {
    uni.hideLoading();
  }, 1000);
  return new Promise((resolve,reject)=>{
    wx.request({
      url: url,
      data: params || {},
      method: method || 'GET',
      header: header,
      success: (res) => {
        clearTimeout(timer);
        uni.hideLoading();
        //处理 res.code
        if (res.data.code == 0) {
          //正常
          resolve(res.data);

        } else if (res.data.code == 1) {
          uni.showToast({
            title: '请求错误',
          })
        }
        else if (res.data.code == 2) {
          //提示
          uni.showModal({
            title: '温馨提示',
            content: `${res.data.msg}`,
            confirmColor: '#ff474f'
          })
        }


      },
      fail: (err) => {
        // console.log(err);
        clearTimeout(timer);
        uni.hideLoading();
        uni.showToast({
          title: '响应失败',
        });
        reject(err);
      },
      //不管是成功还是失败都要执行的函数
      complete: () => {

      }

    });
  })
}

const ajax = {
  get: (url, params, header) => {
    return request(url, 'GET', params, {'content-type': 'application/json'})
  },
  post: (url, params, header) => {
    return request(url, 'POST', params, {'content-type': 'application/x-www-form-urlencoded'})
  }
};

export default ajax;
